package valentini.android.strike;

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;

import org.htmlcleaner.CleanerProperties;
import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;

import android.preference.PreferenceManager;
import android.util.Log;

public class HtmlParser {
	
	// HTML page
	static final String BLOG_URL = "http://xjaphx.wordpress.com/";
	// XPath query
	static final String XPATH_STATS = "//div[@id='blog-stats']/ul/li";

	static boolean err = false;
	
	// oggetto TagNode radice del file html
	private TagNode rootNode;
	
	private static HtmlParser instance = null;
	
	private boolean isStrikeToday = false;
	
	private ArrayList<HashMap<String, String>> items;
	
	private ArrayList<HashMap<String, String>> todaystrikes = new ArrayList<HashMap<String, String>>();;
	
	
	
	public boolean getIsStrikeToday() {
		return isStrikeToday;
	}


	public static HtmlParser getInstance() {
		if (instance == null) {
				instance = new HtmlParser();
				if (err){
					instance=null;
				}
					
		}
		return instance;
	}

	public ArrayList<HashMap<String, String>> getItems() {
		return items;
	}
	
	public ArrayList<HashMap<String, String>> getTodaystrikes() {
		return todaystrikes;
	}

	private HtmlParser() {
		init();
	 }

	public void init() {
		// URL di cui si vuole fare il parsing
		// this.url_str = url_str;

		HtmlCleaner cleaner = new HtmlCleaner();
		CleanerProperties props = cleaner.getProperties();
		props.setAllowHtmlInsideAttributes(true);
		props.setAllowMultiWordAttributes(true);
		props.setRecognizeUnicodeChars(true);
		props.setOmitComments(true);
		
		URL url;
		try {

			url = new URL(Constants.url_str);
			URLConnection conn = url.openConnection();

			this.rootNode = cleaner.clean(new InputStreamReader(conn
					.getInputStream()));
			
			this.items = getElement(Constants.elementName);

		} catch (Exception e) {
			err=true;
		}
	
	}
	
	public  HtmlParser(String url_str) {
		// URL di cui si vuole fare il parsing
		// this.url_str = url_str;

		HtmlCleaner cleaner = new HtmlCleaner();
		CleanerProperties props = cleaner.getProperties();
		props.setAllowHtmlInsideAttributes(true);
		props.setAllowMultiWordAttributes(true);
		props.setRecognizeUnicodeChars(true);
		props.setOmitComments(true);

		URL url;
		try {

			url = new URL(Constants.url_str);
			URLConnection conn = url.openConnection();

			rootNode = cleaner.clean(new InputStreamReader(conn
					.getInputStream()));
			
			this.items = getElement(Constants.elementName);

		} catch (MalformedURLException e) {
			Log.e("Error", e.getMessage());

		} catch (IOException e) {
			Log.e("Error", e.getMessage());
		}
	
	}

	public boolean isStrikeToday() {
		
		boolean result = false;
		Utils util = new Utils();
		
		TagNode Dates[] = rootNode.getElementsByAttValue("class",
				"dataSciopero", true, true);
		Date today = Calendar.getInstance().getTime();
		today = util.removeTime(today);
		SimpleDateFormat formatter = new SimpleDateFormat("dd MMMMM yyyy",
				Locale.ITALY); 
		
		for (int i = 0; i < Dates.length; i++) {
			
			String tmp = Dates[i].getAllChildren().get(0).toString();
			Date date = Calendar.getInstance().getTime();
			 
			try {
				date = formatter.parse(tmp.trim());
				date = util.removeTime(date);
			} catch (ParseException e) {
				e.printStackTrace();
			}
			if ( (today.getTime()) == (date.getTime()) ){
				//if ((today.toString()).equals(date.toString())){
					result = true;
					break;
				}
		}
		return result;
	}

	public boolean isToday(String tmp) {
		
		Utils util = new Utils();
		boolean outcome=false;
		
		Date today = Calendar.getInstance().getTime();
		today = util.removeTime(today);
		SimpleDateFormat formatter = new SimpleDateFormat("dd MMMMM yyyy",
				Locale.ITALY); 

		Date date = Calendar.getInstance().getTime();
		 
		try {
			date = formatter.parse(tmp.trim());
			date = util.removeTime(date);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		if ( (today.getTime()) == (date.getTime()) ){
			outcome = true;
		}
		else
			outcome=false;
		return outcome;
	}
	
	private ArrayList<HashMap<String, String>> getElement(String elementName) {
		ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
		
		TagNode Elements[] = rootNode.getElementsByName(elementName, true);
		TagNode Types[] = rootNode.getElementsByAttValue("class",
				"modoSciopero", true, true);
		TagNode Categories[] = rootNode.getElementsByAttValue("class",
				"categoriaSciopero", true, true);
		TagNode Settori[] = rootNode.getElementsByAttValue("class",
				"settoreSciopero", true, true);

		HashMap<String, String> map = new HashMap<String, String>();
		int j = 0;
		boolean toAdd=false;
		String data = "";
		for (int i = 0; Elements != null && i < Elements.length; i++) {
			
			toAdd=false;
			String date = Elements[i].getAttributeByName("class");

			if (date!="" && date != null && "dataSciopero".equals(date))
				data = Elements[i].getAllChildren().get(0).toString().trim()
				.toUpperCase(Locale.ITALIAN);

			if (date != null && "boxSciopero".equals(date)) {
				
				j = menuItems.size();
				map = new HashMap<String, String>();

				String temp;
				
				if (isBeforeToday(data)){
					continue;
				}

				map.put(Constants.KEY_DATA, data);
				
				if(isToday(data)){
					toAdd=true;
				}

				temp = Categories[j].getAllChildren().get(0).toString().trim();
				map.put(Constants.KEY_CATEGORIA, temp);

				TagNode temp_node = (TagNode) Types[j].getAllChildren().get(1);
				temp = temp_node.getAllChildren().get(0).toString().trim();
				map.put(Constants.KEY_MODALITA, temp);

				temp_node = (TagNode) Settori[j].getAllChildren().get(1);
				temp = temp_node.getAllChildren().get(0).toString();
				map.put(Constants.KEY_SETTORE, temp);

				menuItems.add(map);
				if (toAdd)
					todaystrikes.add(map);

			}

		}

		return menuItems;
	}

	private boolean isBeforeToday(String data) {
		
		Utils util = new Utils();
		boolean outcome=false;
		
		Date today = Calendar.getInstance().getTime();
		today = util.removeTime(today);
		SimpleDateFormat formatter = new SimpleDateFormat("dd MMMMM yyyy",
				Locale.ITALY); 

		Date date = Calendar.getInstance().getTime();
		 
		try {
			date = formatter.parse(data.trim());
			date = util.removeTime(date);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		if ( (today.getTime()) > (date.getTime()) ){
			outcome = true;
		}
		else
			outcome=false;
		return outcome;
	}


	public Set<String> getTodayStrikeSectors() {
		Set<String> out = new HashSet<String>(); 
		for (HashMap<String, String> strike : getTodaystrikes()) {
			if (!out.contains(strike.get(Constants.KEY_CATEGORIA)))	
				out.add(strike.get(Constants.KEY_CATEGORIA));
		}
		return out;
	}
	
}
